﻿using MiniFox.Caching;
using MiniFox.Components;
using MiniFox.Platform.OAuth2.Providers;
using MiniFox.Platform.Providers;

namespace MiniFox.Platform.OAuth2.Services
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class OAuth2ServiceBase : Component
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="authStateManagement">认证状态管理器</param>
        protected OAuth2ServiceBase(IAuthenticationStateManagement authStateManagement)
        {
            this.StateManagement = authStateManagement;
        }
        /// <summary>
        /// 
        /// </summary>
        [AutoWired]
        protected IOAuth2ConfigProvider ConfigProvider
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        [AutoWired]
        protected IPassportTokenProvider TokenProvider { get; set; }
        /// <summary>
        /// 
        /// </summary>
        [AutoWired]
        public ITicketProvider TicketProvider { get; set; }
        /// <summary>
        /// 
        /// </summary>
        protected internal virtual IAuthenticationStateManagement StateManagement
        {
            get;
        }
        /// <summary>
        /// 
        /// </summary>
        protected internal virtual CacheProvider Cache
        {
            get
            {
                return CacheService.DefaultCachingProvider;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public PassportToken PassportToken
        {
            get
            {
                var ticketId = this.StateManagement.AuthTicketID;
                if (string.IsNullOrEmpty(ticketId))
                    return null;
                var token = Cache.Get($"{OpenAuthKey.PASSPORT_TOKEN}-{ticketId}", () => this.TokenProvider.GetPassportToken(ticketId), true);
                if (token == null || token.IsExpired())
                    return null;

                return token;
            }
        }
    }
}
